package com.bullsora.kindlerss.model;

import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;

import javax.persistence.*;
import java.util.Date;
import java.util.List;

@RooJavaBean
@RooToString
@RooJpaActiveRecord(finders = {"findFeedEntrysByLinkEquals", "findFeedEntrysByReceiveDateLessThan"})
public class FeedEntry {

  @ManyToOne
  private FeedUrl feedUrl;

  private String link;

  private String title;

  private String author;

  private String description;

  @Temporal(TemporalType.TIMESTAMP)
  @DateTimeFormat(style = "M-")
  private Date publishedDate;

  @Temporal(TemporalType.TIMESTAMP)
  @DateTimeFormat(style = "M-")
  private Date receiveDate;

  public static boolean existsEntryForFeedUrlWithLink(FeedUrl feedUrl, String link) {
    if (link == null || link.length() == 0) throw new IllegalArgumentException("The link argument is required");
    EntityManager em = FeedEntry.entityManager();
    TypedQuery<FeedEntry> query = em.createQuery("SELECT o FROM FeedEntry AS o WHERE o.link = :link AND o.feedUrl = :feedUrl", FeedEntry.class);
    query.setParameter("link", link);
    query.setParameter("feedUrl", feedUrl);
    List<FeedEntry> resultList = query.getResultList();
    if (resultList.isEmpty()) {
      return false;
    }
    return true;
  }

  public static List<com.bullsora.kindlerss.model.FeedEntry> findNewEntriesForUrl(Date since, FeedUrl url) {
    EntityManager em = FeedEntry.entityManager();
    TypedQuery<FeedEntry> query = em.createQuery("SELECT o FROM FeedEntry AS o WHERE o.receiveDate > :since AND o.feedUrl = :feedUrl", FeedEntry.class);
    query.setParameter("since", since);
    query.setParameter("feedUrl", url);
    return query.getResultList();
  }

  public static void removeFeedEntriesReceivedBefore(Date since) {
    EntityManager em = FeedEntry.entityManager();
    TypedQuery<FeedEntry> query = em.createQuery("DELETE FROM FeedEntry AS fe WHERE fe.receiveDate < :since ", FeedEntry.class);
    query.setParameter("since", since);
    query.executeUpdate();
  }
}
